<template>
  <div id="my-swiper">
    <ul
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
      :style="activeStyle"
    >
      <li v-for="item in swiper" :key="item.id">
        <img :src="item.picUrl" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { getSwiper } from "../../utils/api";
export default {
  // 调用子组件
  components: {},
  data() {
    return {
      swiper: [],
      activeStyle: {
        transition: "none",
        left: "-100%",
      },
      dir: "left", // 标记用户滑动的方向
      startPos: 0, // 记录用户触摸的开始点
      isWork: true, // 标记动画是否能够执行
    };
  },
  mounted() {
    //   渲染页面
    getSwiper().then((res) => {
      this.swiper = res.data;
    });
    // 轮播图
    setInterval(() => {
      this.touchEnd();
    }, 1000);
  },
  // 事件方法
  methods: {
    touchStart(e) {
      this.startPos = e.touches[0].pageX;
    },
    touchMove(e) {
      if (e.touches[0].pageX - this.startPos > 0) {
        this.dir = "right";
      } else {
        this.dir = "left";
      }
    },

    touchEnd() {
      if (this.isWork) {
        this.isWork = false;
        if (this.dir == "right") {
          this.activeStyle = {
            transition: "left 1s",
            left: "0",
          };

          setTimeout(() => {
            let item = this.swiper.pop();
            this.swiper.unshift(item);
            this.activeStyle = {
              transition: "none",
              left: "-100%",
            };
            this.isWork = true;
          }, 1000);
        } else {
          this.activeStyle = {
            transition: "left 1s",
            left: "-200%",
          };

          setTimeout(() => {
            let item = this.swiper.shift();
            this.swiper.push(item);
            this.activeStyle = {
              transition: "none",
              left: "-100%",
            };
            this.isWork = true;
          }, 1000);
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
#my-swiper {
  width: 100%;
  overflow: hidden;
  text-align: center;
  ul {
    width: 300%;
    height: 6rem;
    position: relative;
    > li {
      width: 33.3%;
      height: 6rem;
      float: left;
      text-align: center;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
